<template>
  <div class="function-point-container">
    <!-- 批量导入 -->
    <el-button
        type="primary"
        @click="$refs.excelBtn.click()"
    >批量导入</el-button>
    <el-upload
        v-show="false"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        action
        :auto-upload="false"
        :show-file-list="false"
        :on-change="importData"
    >
      <span ref="excelBtn">导入EXCEL</span>
    </el-upload>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'TestXlx',
  data() {
    return {}
  },
  created() {},
  methods: {
    // 批量导入
    importData(file, fileList) {
      // 拿取文件对象
      const f = file.raw
      // 用 FileReader 来读取
      let reader = new FileReader()
      // 重写 FileReader 上的 readAsBinaryString 方法
      FileReader.prototype.readAsBinaryString = f => {
        let binary = ''
        let wb // 读取完成的数据
        let outdata // 你需要的数据
        let reader = new FileReader()
        reader.onload = e => {
          // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
          let bytes = new Uint8Array(reader.result)
          let length = bytes.byteLength
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          // 接下来就是xlsx了，具体可看api
          wb = XLSX.read(binary, {
            type: 'binary',
            cellDates: false
          })
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          const result = this.generateParam(outdata)
          console.log('result--', result)

          // 下面就进行接口调用了...
        }
        reader.readAsArrayBuffer(f)
      }
      reader.readAsBinaryString(f)
    },
    // 生成导入参数
    generateParam(data) {
      const params = []
      // 这里根据实际表格 title 值、接口参数值，灵活变化
      const parse = {
        姓名: 'answerName',
        密码: 'password',
        手机号: 'phone',
        年龄: 'age',
        性别: 'gender',
        地址: 'address'
      }
      data.forEach(item => {
        let obj = {}
        const keys = Object.keys(parse)
        const itemKeys = Object.keys(item)
        itemKeys.forEach(key => {
          const val = item[key]
          if (keys.includes(key)) {
            obj[parse[key]] = val
          }
        })
        params.push(obj)
      })
      return params
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
